package com.yl.immodule.v

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.MotionEvent
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.Toast
import androidx.annotation.RequiresApi
import androidx.media3.common.MediaItem
import androidx.media3.common.Player
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.bumptech.glide.Glide
import com.camera.base.Log.YLogImpl
import com.camera.base.util.CameraDegreeUtil
import com.camera.base.v.BaseActivity
import com.camera.routemodule.RouterPath
import com.yl.immodule.R
import com.yl.immodule.databinding.ActivityCameraImBinding
import com.yl.immodule.v.models.CameraIMViewModel
import java.io.File

@Route(path = RouterPath.path.im_camera_activity)
class CameraIMActivity : BaseActivity<ActivityCameraImBinding, CameraIMViewModel>() {
    
    companion object {
        private const val TAG = "CameraIMActivity"
        // 用于返回结果的键
        const val RESULT_MEDIA_PATH = "media_path"
    }
    
    private var isRecording = false
    private val handler = Handler(Looper.getMainLooper())
    private var longPressRunnable: Runnable? = null
    
    // 录像最大时长(ms)
    private val MAX_RECORD_TIME = 15000
    // 录像倒计时计数器
    private var recordTimeCounter = 0
    // 录像进度更新频率(ms) - 降低以提高平滑度
    private val PROGRESS_UPDATE_INTERVAL = 16 // 约60fps的刷新率
    // 录像进度更新定时器
    private val updateProgressRunnable = object : Runnable {
        override fun run() {
            if (viewModel.progressUpdateActive.value == true) {
                recordTimeCounter += PROGRESS_UPDATE_INTERVAL
                
                // 通知ViewModel更新进度
                viewModel.updateRecordProgress(PROGRESS_UPDATE_INTERVAL)
                
                // 继续更新进度
                handler.postDelayed(this, PROGRESS_UPDATE_INTERVAL.toLong())
            }
        }
    }
    
    // 视频播放相关
    private var player: ExoPlayer? = null
    private var playerView: PlayerView? = null
    private var isPlaybackMode = false
    private var recordedVideoPath: String? = null
    
    // 图片预览相关
    private var imagePreviewView: ImageView? = null
    
    override fun getLayoutId(): Int {
        return R.layout.activity_camera_im
    }

    override fun getStatusBarColor(): Int {
        return R.color.title_background_color
    }

    override val viewModelClass: Class<CameraIMViewModel>
        get() = CameraIMViewModel::class.java

    override fun loadData() {
        // 数据加载不需要特别实现
    }
    
    override fun initView() {
        // 初始化相机
        loadCamera()

        // 设置数据绑定
        mBinding.viewModel = viewModel
        mBinding.lifecycleOwner = this
        viewModel.mICPInterface?.let { camera ->
            if (!camera.isICPCameraOpen){
                camera.openICPCamera()
            }else{
                loadCamera()
            }

        }
        // 设置关闭按钮点击事件
        mBinding.btnClose.setOnClickListener {
            if (isPlaybackMode) {
                // 在播放模式下，返回录制模式
                exitPlaybackMode()
            } else {
                // 否则退出活动
                finish()
            }
        }
        
        // 设置拍照/录像按钮
        setupCaptureButton()

        
        // 设置取消按钮
        mBinding.btnCancel.setOnClickListener {
            // 取消并返回录制模式
            exitPlaybackMode()
        }
        // 观察摄像头事件
        observeCameraEvents()
        
        // 绑定ViewModel数据
        bindViewModelData()
        
        // 初始化观察者
        initObservers()
        
        // 设置发送和取消按钮
        setupActionButtons()
    }
    
    /**
     * 设置发送和取消按钮
     */
    private fun setupActionButtons() {
        // 设置发送按钮
        mBinding.btnSend.setOnClickListener {
            viewModel.sendMedia()
        }
        
        // 设置取消按钮
        mBinding.btnCancel.setOnClickListener {
            viewModel.exitPlaybackMode()
        }
    }
    
    /**
     * 观察摄像头事件
     */
    private fun observeCameraEvents() {
        viewModel.cameraEvent.observe(this) { event ->
            when (event) {
                is CameraIMViewModel.CameraEvent.ClearSurfaceView -> {
                    // 清空相机预览容器
                    Log.d(TAG, "正在清空相机预览容器")
                    
                    // 清空相机预览容器
                    mBinding.cameraFramelayout.removeAllViews()
                    
                    // 重置播放器视图状态
                    playerView = null
                    player = null
                    imagePreviewView = null
                }
                is CameraIMViewModel.CameraEvent.ReloadCamera -> {
                    // 重新加载相机预览
                    Log.d(TAG, "正在重新加载相机预览")
                    handler.postDelayed({
                        loadCamera()
                    }, 100)
                }
                is CameraIMViewModel.CameraEvent.StartProgressUpdate -> {
                    // 开始更新进度
                    isRecording = true
                    recordTimeCounter = 0
                    handler.post(updateProgressRunnable)
                }
                is CameraIMViewModel.CameraEvent.StopProgressUpdate -> {
                    // 停止更新进度
                    isRecording = false
                    handler.removeCallbacks(updateProgressRunnable)
                }
                is CameraIMViewModel.CameraEvent.LoadVideo -> {
                    // 加载视频
                    loadVideoForPlayback(event.videoPath)
                }
                is CameraIMViewModel.CameraEvent.LoadImage -> {
                    // 加载图片
                    loadImageForPreview(event.imagePath)
                }
                is CameraIMViewModel.CameraEvent.ReleasePlayer -> {
                    // 释放播放器和图片预览
                    releaseMediaResources()
                }
                is CameraIMViewModel.CameraEvent.FinishActivity -> {
                    // 获取要返回的媒体路径
                    when (viewModel.previewType.value) {
                        CameraIMViewModel.PreviewType.VIDEO -> {
                            val videoPath = viewModel.recordedVideoPath.value
                            if (!videoPath.isNullOrEmpty()) {
                                setMediaResult(videoPath)
                            }
                        }
                        CameraIMViewModel.PreviewType.IMAGE -> {
                            val imagePath = viewModel.capturedImagePath.value
                            if (!imagePath.isNullOrEmpty()) {
                                setMediaResult(imagePath)
                            }
                        }
                        else -> {
                            // 如果没有媒体，设置取消结果
                            setResult(Activity.RESULT_CANCELED)
                        }
                    }
                    finish()
                }
            }
        }
        
        // 观察Toast消息
        viewModel.toastString.observe(this) { message ->
            message?.let {
                Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    /**
     * 设置媒体结果
     */
    private fun setMediaResult(mediaPath: String) {
        Log.e(TAG, "setMediaResult: "+mediaPath )
        val intent = Intent()
        intent.putExtra(RESULT_MEDIA_PATH, mediaPath)
        setResult(Activity.RESULT_OK, intent)
    }
    
    /**
     * 加载图片预览
     */
    private fun loadImageForPreview(imagePath: String) {
        Log.d(TAG, "开始加载图片预览: $imagePath")
        try {
            // 检查文件是否存在
            val imageFile = File(imagePath)
            if (!imageFile.exists()) {
                Log.e(TAG, "图片文件不存在: $imagePath")
                Toast.makeText(this, "图片文件不存在", Toast.LENGTH_SHORT).show()
                return
            }
            
            // 释放现有资源但不清空相机预览
            releaseMediaResources()
            
            // 创建全屏图片视图
            imagePreviewView = ImageView(this).apply {
                layoutParams = FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT, 
                    ViewGroup.LayoutParams.MATCH_PARENT
                )
                scaleType = ImageView.ScaleType.CENTER_CROP // 使用CENTER_CROP以全屏显示
            }
            
            // 添加到图片预览容器中而不是根布局
            mBinding.imagePreviewContainer.removeAllViews()
            mBinding.imagePreviewContainer.addView(imagePreviewView)
            mBinding.imagePreviewContainer.visibility = View.VISIBLE
            
            // 使用Glide加载图片并全屏显示
            Glide.with(this)
                .load(imageFile)
                .centerCrop() // 确保填充整个ImageView
                .into(imagePreviewView!!)
            
            Log.d(TAG, "图片全屏加载完成")
        } catch (e: Exception) {
            Log.e(TAG, "加载图片预览失败", e)
            Toast.makeText(this, "加载图片预览失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 更新进度显示
     */
    private fun updateProgressDisplay(progress: Int) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            mBinding.btnCapture.updateProgress(progress)
        }
    }
    
    /**
     * 绑定ViewModel数据
     */
    private fun bindViewModelData() {
        viewModel.recordProgress.observe(this) { progress ->
            updateProgressDisplay(progress)
        }
        
        viewModel.isPlaybackMode.observe(this) { isPlaybackMode ->
            if (isPlaybackMode) {
                mBinding.btnClose.setImageResource(R.drawable.ic_arrow_back)
            } else {
                mBinding.btnClose.setImageResource(R.drawable.ic_arrow_back)
            }
        }
        
        viewModel.previewType.observe(this) { previewType ->
            // 根据预览类型更新UI（如果需要）
            when (previewType) {
                CameraIMViewModel.PreviewType.VIDEO -> {
                    Log.d(TAG, "预览类型: 视频")
                }
                CameraIMViewModel.PreviewType.IMAGE -> {
                    Log.d(TAG, "预览类型: 图片")
                }
                else -> {
                    Log.d(TAG, "预览类型: 无")
                }
            }
        }
    }
    
    /**
     * 初始化观察者
     */
    private fun initObservers() {
        viewModel.isRecording.observe(this) { isRecording ->
            this.isRecording = isRecording
            if (isRecording) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    mBinding.btnCapture.startRecording()
                }
            } else {
                mBinding.btnCapture.stopRecording()
            }
        }
        
        viewModel.videoUri.observe(this) { uri ->
            uri?.let {
                Log.d(TAG, "收到视频URI更新: $uri")
                // 可以使用这个Uri加载视频
                player?.let { exoPlayer ->
                    exoPlayer.setMediaItem(MediaItem.fromUri(uri))
                    exoPlayer.prepare()
                    exoPlayer.play()
                }
            }
        }
        
        viewModel.progressUpdateActive.observe(this) { active ->
            if (active) {
                recordTimeCounter = 0
                handler.post(updateProgressRunnable)
            } else {
                handler.removeCallbacks(updateProgressRunnable)
            }
        }
    }
    
    @RequiresApi(Build.VERSION_CODES.Q)
    @SuppressLint("ClickableViewAccessibility")
    private fun setupCaptureButton() {
        longPressRunnable = Runnable {
            // 开始录像
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                startRecording()
            }
        }
        
        mBinding.btnCapture.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 按下动画
                    mBinding.btnCapture.animatePress()
                    // 设置长按录像延迟
                    handler.postDelayed(longPressRunnable!!, 500)
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 释放动画
                    mBinding.btnCapture.animateRelease()
                    
                    if (handler.hasCallbacks(longPressRunnable!!)) {
                        // 如果长按没有触发，则拍照
                        handler.removeCallbacks(longPressRunnable!!)
                        if (!isRecording) {
                            viewModel.takePhoto()
                        } else {
                            // 如果正在录像，则停止录像
                            stopRecording()
                        }
                    } else if (isRecording) {
                        // 如果正在录像，则停止录像
                        stopRecording()
                    }
                }
            }
            true
        }
    }
    
    @RequiresApi(Build.VERSION_CODES.N)
    private fun startRecording() {
        mBinding.btnCapture.startRecording()
        viewModel.startRecording()
    }
    
    private fun stopRecording() {
        mBinding.btnCapture.stopRecording()
        viewModel.stopRecording()
    }
    
    /**
     * 加载视频进行播放
     */
    private fun loadVideoForPlayback(videoPath: String) {
        Log.d(TAG, "开始加载视频播放: $videoPath")
        try {
            // 检查文件是否存在
            val videoFile = File(videoPath)
            if (!videoFile.exists()) {
                Log.e(TAG, "视频文件不存在: $videoPath")
                Toast.makeText(this, "视频文件不存在", Toast.LENGTH_SHORT).show()
                return
            }
            
            // 释放现有资源
            releaseMediaResources()
            
            // 初始化播放器
            player = ExoPlayer.Builder(this).build()
            
            // 创建播放器视图（如果需要）
            if (playerView == null) {
                Log.d(TAG, "创建新的播放器视图")
                playerView = LayoutInflater.from(this)
                    .inflate(R.layout.view_video_player, null) as PlayerView
                mBinding.cameraFramelayout.addView(playerView)
            } else {
                Log.d(TAG, "使用现有的播放器视图")
                playerView?.visibility = View.VISIBLE
            }
            
            playerView?.player = player
            
            player?.let { exoPlayer ->
                // 设置媒体源
                val mediaItem = MediaItem.fromUri(Uri.fromFile(videoFile))
                exoPlayer.setMediaItem(mediaItem)
                
                // 设置播放监听
                exoPlayer.addListener(object : Player.Listener {
                    override fun onPlaybackStateChanged(state: Int) {
                        if (state == Player.STATE_ENDED) {
                            // 播放结束时循环播放
                            exoPlayer.seekTo(0)
                            exoPlayer.play()
                        }
                    }
                })
                
                // 准备并自动播放
                exoPlayer.prepare()
                exoPlayer.playWhenReady = true
                exoPlayer.repeatMode = Player.REPEAT_MODE_ONE
                
                Log.d(TAG, "播放器已准备并开始播放")
            }
        } catch (e: Exception) {
            Log.e(TAG, "加载视频失败", e)
            Toast.makeText(this, "加载视频失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }
    
    /**
     * 释放媒体资源（视频或图片）
     */
    private fun releaseMediaResources() {
        try {
            // 释放视频播放器资源
            player?.let { exoPlayer ->
                exoPlayer.stop()
                exoPlayer.release()
            }
            player = null
            playerView?.visibility = View.GONE
            
            // 清除图片预览
            imagePreviewView?.setImageDrawable(null)
            imagePreviewView = null
            
            // 隐藏图片预览容器
            mBinding.imagePreviewContainer.removeAllViews()
            mBinding.imagePreviewContainer.visibility = View.GONE
            
        } catch (e: Exception) {
            Log.e(TAG, "释放媒体资源失败", e)
        }
    }

    /**
     * 切换到播放模式
     */
    private fun enterPlaybackMode(videoPath: String) {
        isPlaybackMode = true
        
        // 隐藏录制控件，显示播放控件
        mBinding.recordingControls.visibility = View.GONE
        mBinding.playbackControls.visibility = View.VISIBLE
        
        // 设置返回按钮的功能
        mBinding.btnClose.setImageResource(R.drawable.ic_arrow_back)
        
        // 创建播放器视图
        if (playerView == null) {
            playerView = LayoutInflater.from(this)
                .inflate(R.layout.view_video_player, null) as PlayerView
            mBinding.cameraFramelayout.addView(playerView)
        } else {
            playerView?.visibility = View.VISIBLE
        }
        
        // 初始化播放器
        initializePlayer(videoPath)
    }
    
    /**
     * 退出播放模式，返回录制模式
     */
    private fun exitPlaybackMode() {
        isPlaybackMode = false
        
        // 隐藏播放控件，显示录制控件
        mBinding.playbackControls.visibility = View.GONE
        mBinding.recordingControls.visibility = View.VISIBLE
        
        // 设置关闭按钮的功能
        mBinding.btnClose.setImageResource(R.drawable.ic_arrow_back)
        
        // 停止并释放播放器
        releaseMediaResources()
        
        // 隐藏播放器视图
        playerView?.visibility = View.GONE
    }
    
    /**
     * 初始化视频播放器
     */
    private fun initializePlayer(videoPath: String) {
        player = ExoPlayer.Builder(this).build().also { exoPlayer ->
            playerView?.player = exoPlayer
            
            // 设置媒体源
            val mediaItem = MediaItem.fromUri(Uri.fromFile(File(videoPath)))
            exoPlayer.setMediaItem(mediaItem)
            
            // 设置播放监听
            exoPlayer.addListener(object : Player.Listener {
                override fun onPlaybackStateChanged(state: Int) {
                    if (state == Player.STATE_ENDED) {
                        // 播放结束时循环播放
                        exoPlayer.seekTo(0)
                        exoPlayer.play()
                    }
                }
            })
            
            // 准备并自动播放
            exoPlayer.prepare()
            exoPlayer.playWhenReady = true
            exoPlayer.repeatMode = Player.REPEAT_MODE_ONE
        }
    }
    
    fun loadCamera(){
        if (viewModel.mICPInterface == null) return

        val mSurfaceView = SurfaceView(this@CameraIMActivity)
        mSurfaceView.holder.addCallback(object : SurfaceHolder.Callback {
            override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
                viewModel.mICPInterface?.let {
                     it.addOtherSurface(surfaceHolder.surface, mSurfaceView.width, mSurfaceView.height)
                }
            }

            override fun surfaceChanged(surfaceHolder: SurfaceHolder, i: Int, i1: Int, i2: Int) {
                // 画面尺寸变化时回调
            }

            override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {
                viewModel.mICPInterface?.let {
                    it.removeOtherSurface(surfaceHolder.surface)
                }
            }
        })
        viewModel.mICPInterface?.let {
            it.reLayoutSurfaceView(
                this@CameraIMActivity,
                mBinding.cameraFramelayout, it.recordSize!!,
                if (it.getCameraPreviewGgree() == -1) CameraDegreeUtil.getDisplayOrientation(
                    0
                ) else it.getCameraPreviewGgree(),
                -1, true
            )
        }
        mBinding.cameraFramelayout.addView(mSurfaceView)
    }

    override fun onPause() {
        super.onPause()
        // 暂停时关闭闪光灯
        viewModel.closeFlash()
        if (isRecording) {
            stopRecording()
        }
        if (viewModel.isPlaybackMode.value == true && viewModel.previewType.value == CameraIMViewModel.PreviewType.VIDEO) {
            player?.pause()
        }
    }
    
    override fun onResume() {
        super.onResume()
        if (viewModel.isPlaybackMode.value == true && viewModel.previewType.value == CameraIMViewModel.PreviewType.VIDEO) {
            player?.play()
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 确保在销毁Activity时关闭闪光灯
        viewModel.closeFlash()
        releaseMediaResources()
        if (isRecording) {
            stopRecording()
        }
        handler.removeCallbacksAndMessages(null)
    }
}